﻿using Microsoft.AspNetCore.Mvc;
using Yz.Base;
using Yz.Core.Extensions;
using Yz.DB.EFCore.Dal;
using Yz.Model.Entities;

namespace Yz.Web.Controllers
{
    public class HomeController : BaseController
    {
        private readonly IDbAccess<User> _userDbAccess;

        public HomeController(IDbAccess<User> userDbAccess)
        {
            _userDbAccess = userDbAccess;
        }

        public IActionResult Index()
        {
            return View();
        }

        #region 密码修改
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="vmLogin"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult UpdatePwd(string pwd, string newPwd, string newPwd2)
        {
            int userId = base.UserId;
            if (string.IsNullOrEmpty(pwd))
            {
                return Json(new VmReturn { Suc = false, Msg = "旧密码不能为空！" });
            }
            if (string.IsNullOrEmpty(newPwd) || string.IsNullOrEmpty(newPwd2))
            {
                return Json(new VmReturn { Suc = false, Msg = "新密码和确认密码不能为空！" });
            }
            if (newPwd == pwd)
            {
                return Json(new VmReturn { Suc = false, Msg = "新密码不能和旧密码一样！" });
            }
            if (newPwd != newPwd2)
            {
                return Json(new VmReturn { Suc = false, Msg = "两次输入密码不一致！" });
            }
            pwd = pwd.ToMd5Hash();
            newPwd = newPwd.ToMd5Hash();
            var retCode = ReturnCode.Fail;
            retCode = _userDbAccess.Update(p => p.SetProperty(q => q.LoginPwd, newPwd), p => p.Id == userId && p.LoginPwd == pwd);
            if (retCode == ReturnCode.NoExit)
            {
                return Json(new VmReturn() { Suc = false, Msg = "旧密码不正确！" });
            }
            else if (retCode == ReturnCode.Success)
            {
                return Json(new VmReturn() { Suc = true, Msg = "修改成功！" });
            }
            else
            {
                return Json(new VmReturn() { Suc = false, Msg = "修改失败！" });
            }
        }

        #endregion
    }
}